package com.ciaojian.client.service;

import com.ciaojian.core.enums.business.CouponCodeOriginEnum;
import com.ciaojian.core.enums.business.OrderStatusEnum;
import com.ciaojian.core.model.Order;
import com.ciaojian.core.model.ProductGroup;
import com.ciaojian.core.service.NotifyService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author oxiny
 */
@Service
public class NotifyServiceImpl extends NotifyService {
    @Resource
    private ProductGroupServiceImpl productGroupService;
    @Resource
    private CouponCodeServiceImpl couponCodeService;

    @Override
    public void productGroupNotify(Order order) {
        // 修改订单状态
        order.setStatus(OrderStatusEnum.complete);
        order.setPayTime(new Date());
        order.setPayTotal(order.getGoodsTotal());
        // 根据产品组分解产品
        productGroupService.getById(order.getProductGroupId()).map(ProductGroup::getProductGroupDetailList).ifPresent(
                // 循环
                productGroupDetailList -> productGroupDetailList.forEach(productGroupDetail -> {
                    // 0会员卡 1次卡 2权益 3卡包
                    switch (productGroupDetail.getType()) {
                        case 0:
                            productGroupService.memberHandle(order, productGroupDetail.getProductId());
                            break;
                        case 1:
                            productGroupService.timesCardHandle(order, productGroupDetail.getProductId());
                            break;
                        case 2:
                            productGroupService.memberDetailHandle(order, productGroupDetail.getProductId(), CouponCodeOriginEnum.DOUYIN_WRITE_OFF);
                            break;
                        case 3:
                            productGroupService.couponPackageHandle(order, productGroupDetail.getProductId());
                            break;
                        default:
                            break;
                    }
                })
        );
        order.updateById();
    }

    /**
     * 购买券码回调
     *
     * @param order 订单
     */
    public Boolean buyCouponCodeNotify(Order order) {
        // 给用户券
        Boolean result = couponCodeService.giveSingleCouponCodeV2(order.getCouponId(), order.getUserId(), CouponCodeOriginEnum.BUY_PACKAGE);
        if (result) {
            // 修改订单状态
            order.setStatus(OrderStatusEnum.complete);
            order.setPayTotal(order.getGoodsTotal());
            order.setPayTime(new Date());
            order.setPayType("微信支付");
            return order.updateById();
        }
        return false;
    }
}
